<?php
namespace app\admin\controller;

use think\Controller;
use think\Db;
use app\service\ApiKeyService;

/**
 * API Key管理控制器
 */
class ApiKeyManager extends Controller
{
    /**
     * API Key列表
     */
    public function index()
    {
        try {
            $page = $this->request->param('page', 1);
            $limit = $this->request->param('limit', 20);
            
            $list = Db::connect('db_config2')->name('api_keys')
                ->field('id,api_key,name,description,status,expires_at,last_used_at,usage_count,created_at')
                ->order('created_at desc')
                ->paginate($limit, false, ['page' => $page]);
            
            return json([
                'code' => 1,
                'message' => '查询成功',
                'data' => $list
            ]);
            
        } catch (\Throwable $e) {
            return json([
                'code' => 0,
                'message' => '查询失败: ' . $e->getMessage()
            ]);
        }
    }
    
    /**
     * 创建API Key
     */
    public function create()
    {
        try {
            $data = $this->request->post();
            
            // 验证必填字段
            if (empty($data['name'])) {
                return json(['code' => 0, 'message' => 'API Key名称不能为空']);
            }
            
            // 处理权限
            $permissions = [];
            if (!empty($data['permissions'])) {
                $permissions = is_array($data['permissions']) ? $data['permissions'] : explode(',', $data['permissions']);
            }
            
            // 处理IP白名单
            $ipWhitelist = [];
            if (!empty($data['ip_whitelist'])) {
                $ipWhitelist = is_array($data['ip_whitelist']) ? $data['ip_whitelist'] : explode(',', $data['ip_whitelist']);
                $ipWhitelist = array_map('trim', $ipWhitelist);
            }
            
            $createData = [
                'name' => $data['name'],
                'description' => $data['description'] ?? '',
                'permissions' => $permissions,
                'ip_whitelist' => $ipWhitelist,
                'expires_at' => $data['expires_at'] ?? date('Y-m-d H:i:s', strtotime('+1 year'))
            ];
            
            $result = ApiKeyService::createApiKey($createData);
            
            if ($result) {
                return json([
                    'code' => 1,
                    'message' => 'API Key创建成功',
                    'data' => $result
                ]);
            } else {
                return json(['code' => 0, 'message' => 'API Key创建失败']);
            }
            
        } catch (\Throwable $e) {
            return json([
                'code' => 0,
                'message' => '创建失败: ' . $e->getMessage()
            ]);
        }
    }
    
    /**
     * 禁用API Key
     */
    public function disable()
    {
        try {
            $apiKey = $this->request->param('api_key');
            
            if (empty($apiKey)) {
                return json(['code' => 0, 'message' => 'API Key不能为空']);
            }
            
            $result = ApiKeyService::disableApiKey($apiKey);
            
            if ($result) {
                return json(['code' => 1, 'message' => 'API Key已禁用']);
            } else {
                return json(['code' => 0, 'message' => '禁用失败']);
            }
            
        } catch (\Throwable $e) {
            return json([
                'code' => 0,
                'message' => '禁用失败: ' . $e->getMessage()
            ]);
        }
    }
    
    /**
     * 启用API Key
     */
    public function enable()
    {
        try {
            $apiKey = $this->request->param('api_key');
            
            if (empty($apiKey)) {
                return json(['code' => 0, 'message' => 'API Key不能为空']);
            }
            
            $result = Db::connect('db_config2')->name('api_keys')
                ->where('api_key', $apiKey)
                ->update(['status' => 1]);
            
            if ($result !== false) {
                return json(['code' => 1, 'message' => 'API Key已启用']);
            } else {
                return json(['code' => 0, 'message' => '启用失败']);
            }
            
        } catch (\Throwable $e) {
            return json([
                'code' => 0,
                'message' => '启用失败: ' . $e->getMessage()
            ]);
        }
    }
    
    /**
     * API调用日志
     */
    public function logs()
    {
        try {
            $page = $this->request->param('page', 1);
            $limit = $this->request->param('limit', 50);
            $apiKey = $this->request->param('api_key');
            
            $query = Db::connect('db_config2')->name('api_call_logs');
            
            if ($apiKey) {
                $query->where('api_key', $apiKey);
            }
            
            $list = $query->field('id,api_key,request_id,method,path,client_ip,response_code,response_message,execution_time,created_at')
                ->order('created_at desc')
                ->paginate($limit, false, ['page' => $page]);
            
            return json([
                'code' => 1,
                'message' => '查询成功',
                'data' => $list
            ]);
            
        } catch (\Throwable $e) {
            return json([
                'code' => 0,
                'message' => '查询失败: ' . $e->getMessage()
            ]);
        }
    }
    
    /**
     * API使用统计
     */
    public function stats()
    {
        try {
            // 今日调用统计
            $todayStats = Db::connect('db_config2')->name('api_call_logs')
                ->field('api_key, count(*) as call_count, avg(execution_time) as avg_time')
                ->whereTime('created_at', 'today')
                ->group('api_key')
                ->select();
            
            // 错误统计
            $errorStats = Db::connect('db_config2')->name('api_call_logs')
                ->field('response_code, count(*) as count')
                ->where('response_code', '>=', 400)
                ->whereTime('created_at', 'today')
                ->group('response_code')
                ->select();
            
            // 总体统计
            $totalStats = [
                'total_keys' => Db::connect('db_config2')->name('api_keys')->count(),
                'active_keys' => Db::connect('db_config2')->name('api_keys')->where('status', 1)->count(),
                'today_calls' => Db::connect('db_config2')->name('api_call_logs')->whereTime('created_at', 'today')->count(),
                'today_errors' => Db::connect('db_config2')->name('api_call_logs')->where('response_code', '>=', 400)->whereTime('created_at', 'today')->count()
            ];
            
            return json([
                'code' => 1,
                'message' => '统计查询成功',
                'data' => [
                    'today_stats' => $todayStats,
                    'error_stats' => $errorStats,
                    'total_stats' => $totalStats
                ]
            ]);
            
        } catch (\Throwable $e) {
            return json([
                'code' => 0,
                'message' => '统计查询失败: ' . $e->getMessage()
            ]);
        }
    }
    
    /**
     * 生成签名示例
     */
    public function signatureExample()
    {
        $apiKey = $this->request->param('api_key');
        
        if (empty($apiKey)) {
            return json(['code' => 0, 'message' => 'API Key不能为空']);
        }
        
        try {
            $keyInfo = Db::connect('db_config2')->name('api_keys')
                ->where('api_key', $apiKey)
                ->find();
            
            if (!$keyInfo) {
                return json(['code' => 0, 'message' => 'API Key不存在']);
            }
            
            $method = 'POST';
            $path = '/api/device/command';
            $body = json_encode([
                'target' => ['type' => 'single', 'devices' => ['863780074784151']],
                'commands' => [['cmd_name' => 'reboot']]
            ], JSON_UNESCAPED_UNICODE);
            
            $timestamp = time();
            $signature = ApiKeyService::generateSignature($method, $path, $timestamp, $body, $keyInfo['secret_key']);
            
            return json([
                'code' => 1,
                'message' => '签名示例生成成功',
                'data' => [
                    'method' => $method,
                    'path' => $path,
                    'body' => $body,
                    'headers' => [
                        'Authorization' => 'ApiKey ' . $apiKey,
                        'Timestamp' => $timestamp,
                        'Signature' => $signature,
                        'Content-Type' => 'application/json'
                    ],
                    'curl_example' => "curl -X {$method} 'http://your-domain.com{$path}' \\\n" .
                                    "  -H 'Authorization: ApiKey {$apiKey}' \\\n" .
                                    "  -H 'Timestamp: {$timestamp}' \\\n" .
                                    "  -H 'Signature: {$signature}' \\\n" .
                                    "  -H 'Content-Type: application/json' \\\n" .
                                    "  -d '{$body}'"
                ]
            ]);
            
        } catch (\Throwable $e) {
            return json([
                'code' => 0,
                'message' => '生成失败: ' . $e->getMessage()
            ]);
        }
    }
}
